package com.plusapps.inkwang;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Hashtable;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.plusapps.inkwang.adapter.VideoListAdapter;
import com.plusapps.inkwang.model.Video;

public class VideoListActivity extends Activity {
	
	private ArrayList<Video> videoList;
	
	private ListView listView;
	
	private ProgressDialog progressDialog;
	private final int PROGRESS_DIALOG = 0;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.video_list);

        new backgroundLoadListView().execute();
        
    }
    
    @Override
    protected Dialog onCreateDialog (int id) {
    	switch (id) {
    	case (PROGRESS_DIALOG):
    		progressDialog = new ProgressDialog(this);
    		progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    		progressDialog.setMessage("Now loading..");
    		return progressDialog;
    	}
    	return null;
    }
    
    
    protected ArrayList<Video> makeVideoListFromVimeo () {
    	ArrayList<Video> list = new ArrayList<Video>();

    	try {
    	
	    	URL url = new URL("http://vimeo.com/api/v2/inkwang/videos.xml");
	    	HttpURLConnection conn = (HttpURLConnection) url.openConnection();
	    	InputStream is = conn.getInputStream();
	    	
	    	SAXBuilder builder = new SAXBuilder();
	    	Document doc = builder.build(is);
	    	Element rootElement = doc.getRootElement();
	
	    	for (Object o : rootElement.getChildren()) {
	    		Element ele = (Element)o;
	    		Video v = new Video();
	    		
	    		v.setTitle( ele.getChild("title").getValue() );
	    		v.setURL( ele.getChild("mobile_url").getValue() );
	    		v.setThumbnailURL( ele.getChild("thumbnail_small").getValue() );
	    		v.setVid( ele.getChild("id").getValue() );
	    		v.setDuration( Integer.parseInt(ele.getChild("duration").getValue()) );
	    		v.setLikesCount( Integer.parseInt(ele.getChild("stats_number_of_likes").getValue()) );
	    		v.setPlaysCount( Integer.parseInt(ele.getChild("stats_number_of_plays").getValue()) );
	    		v.setCommentsCount( Integer.parseInt(ele.getChild("stats_number_of_comments").getValue()) );
	
	    		list.add(v);
	    	}
	    	
    	} catch (Exception e) {
    		Log.e(this.getClass().getName(), e.getMessage());
    	}
    	
    	return list;
    }

    
    
    private class backgroundLoadListView extends AsyncTask<Void, Void, Void> {
    	
    	private Activity parentContext = VideoListActivity.this;
    	
    	@Override
    	protected void onPostExecute (Void result) {
			VideoListAdapter adapter = new VideoListAdapter(parentContext, R.layout.video_list_item_1, videoList);
            listView = (ListView) findViewById(R.id.video_list_view);
            listView.setAdapter(adapter);

            listView.setOnItemClickListener(new OnItemClickListener () {
    			@Override
    			public void onItemClick(AdapterView<?> av, View v, int position, long id) {
    				Video video = (Video) av.getItemAtPosition(position);
    				Intent intent = new Intent("android.intent.action.VIEW", Uri.parse(video.getURL()));
    				v.getContext().startActivity(intent);
    			}
            });
    		
            progressDialog.dismiss();
            parentContext.removeDialog(PROGRESS_DIALOG);
    	}
    	
    	@Override
    	protected void onPreExecute () {
    		parentContext.showDialog(PROGRESS_DIALOG);
    	}

		@Override
		protected Void doInBackground(Void... params) {
	        videoList = makeVideoListFromVimeo();
	        preLoadImages();

			return null;
		}
    	
    }
    
    
    private void preLoadImages () {
    	for (Video v : videoList) {
    		ImageCache.read(v.getVid(), v.getThumbnailURL());
    	}
    }
    

	public static class ImageCache {
		static Hashtable<String, Bitmap> cache = new Hashtable<String, Bitmap>();
		
		public static Bitmap read (String vid, String srcURL) {
			Bitmap b = cache.get(vid);
			if (b == null) {
				try {
					URL url = new URL(srcURL);
					HttpURLConnection conn = (HttpURLConnection) url.openConnection();
					b = BitmapFactory.decodeStream(conn.getInputStream());
					cache.put(vid, b);
				} catch (Exception e) {
					Log.d("ImageCache", e.getMessage());
				}
			}
			return b;
		}
	}


}
